package com.tkjt.pms.modules.kpiAudit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.calc.core.AuditStatusWatcher;
import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.*;
import com.tkjt.pms.common.vos.RequestJson;
import com.tkjt.pms.modules.common.mapper.TkIndexValueAdjustMapper;
import com.tkjt.pms.modules.common.service.*;
import com.tkjt.pms.modules.kpiAudit.model.AuditDetailsResponseModel;
import com.tkjt.pms.modules.kpiAudit.service.TkAuditService;
import com.tkjt.pms.modules.kpiAudit.thread.MakeMirrorsThread;
import com.tkjt.pms.modules.manageWeight.mapper.WeightMapper;
import com.tkjt.pms.modules.manageWeight.service.WeightService;
import com.tkjt.pms.server.common.DepartUserChangeService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.YearMonth;
import java.util.*;

@RestController
@RequestMapping("/api/pms/kpiAudit")
public class TkAuditController {

    @Autowired
    TkAuditService tkAuditService;
    @Autowired
    TkIndexValueService tkIndexValueService;
    @Autowired
    TkIndexInfoService tkIndexInfoService;
    @Autowired
    ISysDepartService sysDepartService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    TkIndexValueAuditService tkIndexValueAuditService;
    @Autowired
    private TkDataConfigService tkDataConfigService;
    @Autowired
    private AuditStatusWatcher auditStatusWatcher;
    @Autowired
    TkIndexValueAdjustMapper tkIndexValueAdjustMapper;
    @Autowired
    private TkDepartGroupService tkDepartGroupService;
    @Autowired
    private TkIndexValueMirrorServiceI tkIndexValueMirrorService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private DepartUserChangeService departUserChangeService;

    @Autowired
    private WeightMapper weightMapper;
    /**
     * 绩效审核-绩效审核记录
     */
    @RequestMapping("/auditRecords")
    public Result auditRecords(HttpServletRequest httpServletRequest) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        try {
            return tkAuditService.getAuditList(loginUser,httpServletRequest,"auditRecords");
        }catch (Exception e){e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }


    /**
     * 绩效审核-列表信息
     */
    @RequestMapping("auditDatagrid")
    public Result auditDatagrid(HttpServletRequest httpServletRequest) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        try {
            return tkAuditService.getAuditList(loginUser,httpServletRequest,"auditDatagrid");
        }catch (Exception e){e.printStackTrace();
            return Result.error("获取数据异常");
        }
    }


    /**
     * 绩效审核-绩效详情
     */
    @RequestMapping("auditDetails")
    public Result auditDetails(HttpServletRequest httpServletRequest) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        RequestJson requestJson = EsJsonUtils.getRequestJsonObject(httpServletRequest);
        String indexYearMonth = requestJson.getString("indexYearMonth");
        String indexGroup = requestJson.getString("indexGroup");//绩效归属: C: 一线单位 , G：养康本部
        Map<String,Object> param = new HashMap<>();
        param.put("auditShow","1");
        String detailsTitle;
        if ("A01A01A01".equals(indexGroup)) {
            detailsTitle = "【一线单位(" + indexYearMonth.substring(0, 4) + ")】-绩效详情";
            param.put("indexGroup","C");//指标归属(1:事业群;2:社区&医院)',
        } else {
            detailsTitle = "【养康本部(" + indexYearMonth.substring(0, 4) + ")】-绩效详情";
            param.put("indexGroup","G");//指标归属(1:事业群;2:社区&医院)',
        }
        List<TkIndexInfo> singleList = tkIndexInfoService.selectArrtsByParam(param);
        String currentYearMonth = EsDateUtils.getIndexYearMonth(new Date());
        AuditDetailsResponseModel model = new AuditDetailsResponseModel();
        List<AuditDetailsResponseModel.ItemsBean> items = new ArrayList<>();
        List<Map<String, String>> values = new ArrayList<>();
        String[] roleCodes = {"ykgm"};
        List<String> userNames = sysUserMapper.selectUserNameByRoleCodes(roleCodes);
        userNames.add("system");
        for (TkIndexInfo indexInfo : singleList) {
            String indexValueCode = indexInfo.getIndexValueCode();
            Map<String, String> map = new HashMap<>();
            map.put("indexCodeName", indexInfo.getIndexName());
            map.put("indexCode", indexInfo.getIndexCode());
            map.put("indexValueName", indexInfo.getIndexValueName());
            map.put("indexValueCode", indexInfo.getIndexValueCode());
            if(currentYearMonth.equals(indexYearMonth)){
                QueryWrapper<TkIndexValue> qwValue = new QueryWrapper<>();
                qwValue.eq("INDEX_VALUE_CODE", indexValueCode);
                qwValue.eq("DATA_TYPE", dataType);
                qwValue.in("INDEX_EXECUTOR", userNames);
                List<TkIndexValue> tempList = tkIndexValueService.list(qwValue);
                for (TkIndexValue temp : tempList) {
                    String indexDepart = temp.getIndexDepart();//被评分组织机构
                    String indexScorer = StringUtils.isNotEmpty(temp.getIndexScorer())? "-"+temp.getIndexScorer():"";//被评分人
                    String itemCode = indexDepart + indexScorer;

                    String makeGradeString;
                    if (indexInfo.getIndexValueFormat() == 3) {
                        makeGradeString = DepartCode.changeFormate(temp.getMTotal());
                    } else {
                        makeGradeString = DepartCode.formateForDouble(temp.getMTotal()).toString();
                    }
                    map.put(itemCode, makeGradeString);
                }
            }else{
                QueryWrapper<TkIndexValueMirror> qwValue = new QueryWrapper<>();
                qwValue.eq("INDEX_VALUE_CODE", indexValueCode);
                qwValue.eq("DATA_TYPE", dataType);
                qwValue.eq("MIRROR_CODE", "MC"+indexYearMonth);
                qwValue.in("INDEX_EXECUTOR", userNames);
                List<TkIndexValueMirror> tempList = tkIndexValueMirrorService.list(qwValue);
                for (TkIndexValueMirror temp : tempList) {
                    String indexDepart = temp.getIndexDepart();//被评分组织机构
                    String indexScorer = StringUtils.isNotEmpty(temp.getIndexScorer())? "-"+temp.getIndexScorer():"";//被评分人
                    String itemCode = indexDepart + indexScorer;

                    String makeGradeString;
                    if (indexInfo.getIndexValueFormat() == 3) {
                        makeGradeString = DepartCode.changeFormate(temp.getMTotal());
                    } else {
                        makeGradeString = DepartCode.formateForDouble(temp.getMTotal()).toString();
                    }
                    map.put(itemCode, makeGradeString);
                }
            }
            map.put("showColor","0");
            if(indexInfo.getIndexValueAttr().equals(InfoAttrUtil.XIAO_JI) || indexInfo.getIndexValueAttr().equals(InfoAttrUtil.ZONG_JI)){
                map.put("showColor","1");
            }
            values.add(map);
        }
        //添加表头
        AuditDetailsResponseModel.ItemsBean itemsBean = new AuditDetailsResponseModel.ItemsBean();
        itemsBean.setCode("indexCodeName");
        itemsBean.setName("指标");
        items.add(itemsBean);
        /*itemsBean = new AuditDetailsResponseModel.ItemsBean();
        itemsBean.setCode("indexCode");
        itemsBean.setName("指标编码");
        items.add(itemsBean);*/
        itemsBean = new AuditDetailsResponseModel.ItemsBean();
        itemsBean.setCode("indexValueName");
        itemsBean.setName("数据项");
        items.add(itemsBean);
        if(currentYearMonth.equals(indexYearMonth)){
            QueryWrapper<TkIndexValue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_TYPE", dataType);
            queryWrapper.in("INDEX_EXECUTOR", userNames);
            queryWrapper.likeRight("INDEX_DEPART",indexGroup);
            queryWrapper.groupBy("INDEX_DEPART", "INDEX_SCORER");
            List<TkIndexValue> list = tkIndexValueService.list(queryWrapper);
            for (TkIndexValue t : list) {
                String indexDepart = t.getIndexDepart();//被评分组织机构
                String indexScorer = t.getIndexScorer();//被评分人
                String orgName = sysDepartService.queryOrgNameByOrgCode(indexDepart);
                QueryWrapper<TkDepartGroup> groupQueryWrapper = new QueryWrapper<>();
                groupQueryWrapper.lambda().eq(TkDepartGroup::getIndexDepart,indexDepart);
                TkDepartGroup tkDepartGroup = tkDepartGroupService.getOne(groupQueryWrapper);
                if(indexDepart.contains("A01A01A01A") && tkDepartGroup.getDepartBiz().equals("ATRT1000")){
                    continue;
                }
                String realName="";
                if(StringUtils.isNotBlank(indexScorer)){
                    SysUser sysUser = sysUserService.getUserByName(indexScorer);
                    if(sysUser != null){
                        indexScorer= "-"+indexScorer;
                        realName="(" + sysUser.getRealname() + ")";
                    }
                }else{
                    indexScorer="";
                }
                itemsBean = new AuditDetailsResponseModel.ItemsBean();
                itemsBean.setCode(indexDepart + indexScorer);
                itemsBean.setName(orgName + realName);
                items.add(itemsBean);
            }
        }else{
            QueryWrapper<TkIndexValueMirror> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_TYPE", dataType);
            queryWrapper.in("INDEX_EXECUTOR", userNames);
            queryWrapper.likeRight("INDEX_DEPART",indexGroup);
            queryWrapper.eq("MIRROR_CODE", "MC"+indexYearMonth);
            queryWrapper.groupBy("INDEX_DEPART", "INDEX_SCORER");
            List<TkIndexValueMirror> list = tkIndexValueMirrorService.list(queryWrapper);
            Map<String,Object> oldUserParam = new HashMap<>();
            for (TkIndexValueMirror t : list) {
                String indexDepart = t.getIndexDepart();//被评分组织机构
                String indexScorer = t.getIndexScorer();//被评分人
                String orgName = sysDepartService.queryOrgNameByOrgCode(indexDepart);
                QueryWrapper<TkDepartGroup> groupQueryWrapper = new QueryWrapper<>();
                groupQueryWrapper.lambda().eq(TkDepartGroup::getIndexDepart,indexDepart);
                TkDepartGroup tkDepartGroup = tkDepartGroupService.getOne(groupQueryWrapper);
                if(indexDepart.contains("A01A01A01A") && tkDepartGroup.getDepartBiz().equals("ATRT1000")){
                    continue;
                }
                String realName="";
                if(StringUtils.isNotBlank(indexScorer)){
                    SysUser sysUser = sysUserService.getUserByName(indexScorer);
                    if(sysUser != null){
                        indexScorer= "-"+indexScorer;
                        realName="(" + sysUser.getRealname() + ")";
                    }else{
                        oldUserParam.put("indexDepart",indexDepart);
                        oldUserParam.put("beforeUserCode",indexScorer);
                        oldUserParam.put("yearMonth",indexYearMonth);
                        realName = departUserChangeService.selectOldUserNameByParam(oldUserParam);
                        realName="(" + realName + ")";
                        indexScorer= "-"+indexScorer;
                    }
                }else{
                    indexScorer="";
                }
                itemsBean = new AuditDetailsResponseModel.ItemsBean();
                itemsBean.setCode(indexDepart + indexScorer);
                itemsBean.setName(orgName + realName);
                items.add(itemsBean);
            }
        }


        model.setDetailsTitle(detailsTitle);
        model.setItems(items);
        model.setValues(values);
        return Result.ok(model);
    }


    @RequestMapping("auditAction")
    public Result<?> auditAction(HttpServletRequest httpServletRequest){
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(loginUser==null) {
            return Result.error("用户非法！");
        }
        String dataType = tkDataConfigService.getDataType(loginUser.getUsername());
        RequestJson request = EsJsonUtils.getRequestJsonObject(httpServletRequest);
        String indexYearMonth = request.getString("indexYearMonth");
        String indexGroup = request.getString("indexGroup");
        String auditType = request.getString("auditType");
        String auditComments = request.getString("auditComments");
        String auditStep = request.getString("auditStep");

        QueryWrapper<TkIndexValueAudit> qw = new QueryWrapper<>();
        qw.eq("DATA_TYPE",dataType);
        String weightIndexGroup = "G".equals(indexGroup)?"1":"2";
        if(!indexGroup.contains("A01A01")){
            indexGroup = "G".equals(indexGroup)?"A01A01A02":"A01A01A01";
        }
        qw.eq("INDEX_GROUP",indexGroup);
        qw.eq("INDEX_VALUE_Y",indexYearMonth.substring(0,4));
        qw.eq("INDEX_VALUE_M",indexYearMonth.substring(4));
        TkIndexValueAudit tkIndexValueAudit = tkIndexValueAuditService.getOne(qw);
        if(tkIndexValueAudit != null){
            if("atSubmit".equals(auditType)){
                //提交审核
                tkIndexValueAudit.setAuditStatus("2");
            }else{
                //审核
                tkIndexValueAudit.setAuditComments(auditComments);
                if("atAccept".equals(auditType)){
                    //审核通过  生成镜像数据
                    if("1".equals(auditStep)){
                        //初审审核通过
                        tkIndexValueAudit.setAuditStatus("0");
                    }else{
                        //终审审核通过
                        tkIndexValueAudit.setAuditStatus("3");
                        //删除汇总列修改标识数据
                        QueryWrapper<TkIndexValueAdjust> adjustQueryWrapper = new QueryWrapper<>();
                        adjustQueryWrapper.lambda().eq(TkIndexValueAdjust::getWhich,"mTotal");
                        adjustQueryWrapper.lambda().eq(TkIndexValueAdjust::getDataType,dataType);
                        adjustQueryWrapper.lambda().likeRight(TkIndexValueAdjust::getIndexDepart,indexGroup);
                        tkIndexValueAdjustMapper.delete(adjustQueryWrapper);
                    }
                    Map<String,Object> map = new HashMap<>();
                    map.put("year",indexYearMonth.substring(0,4));
                    map.put("currentMonthWeight","WEIGHT_M"+indexYearMonth.substring(4));
                    int nextMonth = indexYearMonth.substring(4).startsWith("0") ? Integer.valueOf(indexYearMonth.substring(5))+1 : Integer.valueOf(indexYearMonth.substring(4))+1;
                    String nextMonthStr = nextMonth < 10 ? "0"+nextMonth : String.valueOf(nextMonth);
                    map.put("nextMonthWeight","WEIGHT_M"+nextMonthStr);

                    map.put("weightIndexGroup",weightIndexGroup);
                    weightMapper.updateLastMonthWeightByParam(map);
                    String mirrorCode = TkIndexUtils.getMirrorCode(new Date());
                    new Thread(new MakeMirrorsThread(mirrorCode, tkIndexValueAudit.getIndexGroup(),dataType, tkIndexValueAuditService, auditStatusWatcher)).start();
                }else if("atReject".equals(auditType)){
                    //审批退回
                    tkIndexValueAudit.setAuditStatus("4");
                }
                tkIndexValueAudit.setAuditTime(new Date());

            }
            tkIndexValueAudit.setSubmitTime(new Date());
            tkIndexValueAuditService.saveOrUpdate(tkIndexValueAudit);
        }
        return Result.ok();
    }

}
